<template>
  <div class="navbar">
    <div class="logo" @click="router.push('/')">新闻网站</div>
    <div class="nav-links">
      <template v-if="isLoggedIn">
        <span class="username">{{ username }}</span>
        <el-button type="danger" @click="handleLogout">退出登录</el-button>
      </template>
      <template v-else>
        <el-button type="primary" @click="router.push('/login')">登录</el-button>
        <el-button @click="router.push('/register')">注册</el-button>
      </template>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import emitter from '../utils/eventBus'

const router = useRouter()
const isLoggedIn = ref(false)
const username = ref('')

// 检查登录状态
const checkLoginStatus = () => {
  const token = localStorage.getItem('token')
  if (token) {
    try {
      const payload = JSON.parse(atob(token.split('.')[1]))
      username.value = payload.username
      isLoggedIn.value = true
      // 如果是管理员，添加标识
      if (payload.role === 'admin') {
        username.value = `${payload.username} (管理员)`
      }
    } catch (error) {
      console.error('Error parsing token:', error)
      localStorage.removeItem('token')
      isLoggedIn.value = false
      username.value = ''
    }
  } else {
    isLoggedIn.value = false
    username.value = ''
  }
}

// 处理退出登录
const handleLogout = () => {
  localStorage.removeItem('token')
  isLoggedIn.value = false
  username.value = ''
  emitter.emit('loginStatusChanged', { isLoggedIn: false, user: null })
  router.push('/login')
  ElMessage.success('已退出登录')
}

// 监听登录状态变化
onMounted(() => {
  checkLoginStatus()
  emitter.on('loginStatusChanged', (data) => {
    isLoggedIn.value = data.isLoggedIn
    if (data.isLoggedIn && data.user) {
      username.value = data.user.username
      // 如果是管理员，在用户名后添加标识
      if (data.user.role === 'admin') {
        username.value += ' (管理员)'
      }
    } else {
      username.value = ''
    }
  })
})
</script>

<style scoped>
.navbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 1rem 2rem;
  background-color: #fff;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.logo {
  font-size: 1.5rem;
  font-weight: bold;
  color: #409EFF;
  cursor: pointer;
}

.nav-links {
  display: flex;
  gap: 1rem;
  align-items: center;
}

.username {
  color: #409EFF;
  font-weight: 500;
  margin-right: 0.5rem;
}

.el-button {
  margin-left: 0.5rem;
}
</style> 